package com.codeyang.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codeyang.constant.NoticeConstant;
import com.codeyang.domain.Notice;
import com.codeyang.mapper.NoticeMapper;
import com.codeyang.service.NoticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 描述: TO-删除标志-DO
 *
 * @author CodeYang_Site
 * @version 2021/5/26 13:53
 */
@CacheConfig(cacheNames = "com.codeyang.service.impl.NoticeServiceImpl")
@Slf4j
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {


    @Autowired
    private NoticeMapper noticeMapper;

    /**
     * 新增公告
     *
     * @param entity
     * @return
     */
    @CacheEvict(NoticeConstant.NOTICE_PREFIX)
    @Override
    public boolean save(Notice entity) {
        log.info("新增公告{}", JSON.toJSONString(entity));
        entity.setShopId(1L);
        entity.setUpdateTime(new Date());
        if (entity.getStatus().equals(1)) {
            entity.setPublishTime(new Date());
        }
        return super.save(entity);
    }

    /**
     * 获取系统主体公告
     * 肯定要缓存,而且不需要关注用户是否登录,只需要关注公告的新增和删除即可
     *
     * @return
     */
    @Cacheable(key = NoticeConstant.NOTICE_PREFIX)
    @Override
    public List<Notice> findTopNotices() {
        List<Notice> notices = noticeMapper.selectList(
                new LambdaQueryWrapper<Notice>()
                .eq(Notice::getStatus,1)
                .eq(Notice::getShopId,1)
                .orderByDesc(Notice::getUpdateTime)
        );


        return notices;
    }
}
